package cn.edu.ctbu.shiyan07.webapi;

import cn.edu.ctbu.shiyan07.core.PageUtils;
import cn.edu.ctbu.shiyan07.domain.Student;
import cn.edu.ctbu.shiyan07.service.StudentService;
import cn.edu.ctbu.shiyan07.utils.RUtil;
import cn.edu.ctbu.shiyan07.vo.R;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/webapi/student")
public class StudentRestController {
    @Autowired
    private StudentService studentService;

    /**
     * 读取的url:webapi/student/list
     * @return
     */
    @GetMapping("/list")
    public R<Page<Student>> list(int page, int size){
        Pageable pageable=PageRequest.of(page,size,Sort.by("id").descending());
        return RUtil.success(studentService.findAll(pageable));
    }
    @GetMapping("/validateUser")
    public R valideNumbersAndPassword(String numbers,String password) throws Exception{
        return RUtil.success(studentService.validateUsernameAndPassword(numbers,password));
    }
    /**
     * 分页，读取全部内容
     * @return
     */
    @GetMapping("/getbypage")
    public PageUtils getByPage(@RequestParam(value = "page",defaultValue = "0") Integer page,
                               @RequestParam(value = "size",defaultValue = "10") Integer size,
                               @RequestParam(value = "name",defaultValue = "") String name,
                               @RequestParam(value = "farm",defaultValue = "") String farm){
        //按id排倒序
        Sort sort=Sort.by(Sort.Direction.DESC,"id");
        Page<Student>studentPage;
        if (StringUtils.isEmpty(name)){
            Pageable pageable=PageRequest.of(page,size,sort);
            studentPage=studentService.findAll(pageable);
        }else if (farm.equals("姓名")&&!StringUtils.isEmpty(name)){
            Student student=new Student();
            student.setName(name);
            Pageable pageable=PageRequest.of(page,size,sort);
            ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Student>example=Example.of(student,matcher);
            studentPage=studentService.findAll(example,pageable);
        }else{
            Student student=new Student();
            student.setNumbers(name);
            Pageable pageable=PageRequest.of(page,size,sort);
            ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("numbers",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Student>example=Example.of(student,matcher);
            studentPage=studentService.findAll(example,pageable);
        }


        PageUtils pageUtils=new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return pageUtils;
    }
    /**
     * 新增学生方法 /webapi/student/insert
     * @param student
     * @return
     */
    @PostMapping("/insert")
    public R insert(@Valid Student student, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            String errormsg=bindingResult.getFieldError().getDefaultMessage();
            log.info("新增学生时出现错误！{}",errormsg);
            return RUtil.error(-10,errormsg);
        }
        studentService.insert(student);
        return RUtil.success();
    }
//    public int insert(@Valid Student student, BindingResult bindingResult){
//        if (bindingResult.hasErrors()){
//
//            log.info(bindingResult.getFieldError().getDefaultMessage());
//            return -1;
//        }
//        studentService.insert(student);
//        Integer myid=student.getId();
//        return myid.intValue();
//    }
    /**
     * 更新学生方法 /webapi/student/update
     * @param student
     * @return
     */
    @PutMapping("/update")
    public Student update(Student student){
        //读旧数据
        Student oldstudent=studentService.getById(student.getId());
        if(StringUtils.isEmpty(student.getPassword()))
        {
            //没有新密码，沿用旧密码
            student.setPassword(oldstudent.getPassword());
        }
        student=studentService.update(student);
        return student;
    }
    /**
     * 删除学生方法 /webapi/student/delete
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Integer id){

        studentService.delete(id);
    }
    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id){
        Student student=studentService.getById(id);
        student.setPassword("");
        return student;
    }
//    @GetMapping("/read/{name}")
//    public List<Student> read(@PathVariable String name){
//        List<Student> student=studentService.findByNameLike(name+"%");
//        return student;
//    }
}
